package Selection;

import GA.Algorithm;
import GA.Chromosome;
import GA.Selection;

public class ProbDisowned implements Selection{
	
	/**
	 *  This method is based on the idea of the probabilist tournament. 
	 *  First of all population is sorted by descending fitness, after that a number between [0..1] is rolled.
	 *  If this number is greater than 'p' (probability constant [0.5, 1]) a random chromosome from the second half 
	 *  (diswoned-bad half) is selected. If it's less than 'p' a chromosome from first half is selected.
	 *  That is repeated till the full new population has been selected
	 */
	
	double p;	// Probability between 0.5..1
	
	public ProbDisowned(){
		this.p = 0.7;	// Default value
	}
	
	public ProbDisowned(double p){
		this.p = p;
	}

	public Chromosome[] selection(Chromosome[] population, int populationSize) {
		Chromosome[] newPopulation = new Chromosome[populationSize];
		
		// Sort population
		AuxFunctions.PopulationFun.sortPopulation(population);
		// Select new Population
		int index;
		double r;
		for (int i = 0; i < populationSize; i++){
			r = Algorithm.random.nextDouble();	// random number between 0..1
			if (r > p)	// diswoned half
				index = (populationSize / 2) + Algorithm.random.nextInt(populationSize / 2);
			else
				index = Algorithm.random.nextInt(populationSize / 2);
			newPopulation[i] = population[index].clone();
		}
		return newPopulation;
	}
	
	

}
